<template>
	<div class="app-container" v-loading="loading">

		<div class="search-container  app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">

					<el-col :span="3">
						<el-tree-select placeholder="请选择党支部" v-model="queryParams.did" clearable
							:default-expand-all="true" :data="dzbOptions" :props="{
					  label: 'name',
					  children: 'children',
					  value: 'id',
					}" filterable check-strictly :render-after-expand="false" />
					</el-col>
					<el-col :span="3">
						<el-select placeholder="请选择职位" clearable v-model="queryParams.role">
							<el-option label="书记" value="1" />
							<el-option label="副书记" value="2" />
							<el-option label="委员" value="3" />
							<el-option label="正式党员" value="4" />
							<el-option label="预备党员" value="5" />
						</el-select>
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
					</el-col>

					<el-col :span="6">
						<el-button :loading="loading" type="primary" @click="handleQuery"><template
								#icon><i-ep-search /></template>查询</el-button>
					</el-col>
				</el-row>
				<FilterColumn class="filtBox" @handleRefresh="resetQuery()" :strtype="strtype"></FilterColumn>
			</div>
		</div>

		<el-card shadow="never">
			
			
			<div class="action-row">
				<el-button v-hasPerm="['Dangwei/save']" @click="handleDo('','act_add')" type="primary" plain><template
						#icon><i-ep-plus /></template>新增</el-button>
				<el-button v-hasPerm="['Dangwei/update']" @click="handleDo('', 'act_edit')"
					:disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)"
					plain><template #icon><i-ep-edit /></template>修改</el-button>
				<el-button v-hasPerm="['Dangwei/delete']" @click="handleDo('', 'act_del')"
					:disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)"
					plain><template #icon><i-ep-delete /></template>删除</el-button>

			</div>


			<el-table ref="dataTableRef" v-loading="loading" :data="tableData" align="center" border
				:show-overflow-tooltip="true" :scrollbar-always-on="true" @cell-mouse-enter="rowMouse"
				@cell-mouse-leave="menuLineVisible=false" @selection-change="handleSelectionChange">
				<el-table-column type="selection" align="center" width="55" />
				<template v-for="(item,index) in cColumnsList()" :key='index'>
					<el-table-column :label="item.label" :align="item.align" :prop="item.prop" :width="item.width"
						:min-width="item.minwidth">
						<template v-if="item.prop == 'role'" #default="scope">
							<el-tag v-if="scope.row.role == 4" type="success">正式党员</el-tag>
							<el-tag v-else-if="scope.row.role == 5" type="info">预备党员</el-tag>
							<el-tag v-else>{{scope.row.position}}</el-tag>
						</template>
						<template v-if="item.prop == 'image'" #default="scope">
							<el-image v-if="scope.row.image" style="width: 25px; height: 25px" :src="scope.row.image"
								:zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[scope.row.image]"
								fit="contain" />
						</template>
					</el-table-column>
				</template>


			</el-table>

			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
				v-model:limit="queryParams.limit" @pagination="handleQuery" />
		</el-card>

		<!-- 表单弹窗 -->
		<el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" @close="closeDialog">
			<el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">


				<el-row :gutter="12">
					<el-col :span="12">
						<el-form-item label="党支部" prop="did">
							<el-tree-select v-model="formData.did" placeholder="选择党支部" :default-expand-all="true"
								:data="dzbOptions" :props="{
			     label: 'name',
			     children: 'children',
			     value: 'id',
			   }" filterable check-strictly :render-after-expand="false" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="角色" prop="role">

							<el-select v-model="formData.role" clearable placeholder="请选择角色">
								<el-option label="书记" :value="1" />
								<el-option label="副书记" :value="2" />
								<el-option label="委员" :value="3" />
								<el-option label="正式党员" :value="4" />
								<el-option label="预备党员" :value="5" />

							</el-select>
					

						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="姓名" prop="name">
							<el-input v-model="formData.name" placeholder="请输入姓名" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="职位" v-if="formData.role < 4" prop="position">
							<el-input v-model="formData.position" placeholder="请输入职位" />
						</el-form-item>
						
						
					</el-col>
				</el-row>

				<el-row>

					<el-col :span="12">
						<el-form-item label="性别" prop="gender">
							<el-select v-model="formData.gender" clearable placeholder="请选择性别">
								<el-option label="男" :value="0" />
								<el-option label="女" :value="1" />
							</el-select>
						</el-form-item>
						
					</el-col>

					<el-col :span="12">
						<el-form-item label="民族" prop="nation">
							<el-input v-model="formData.nation" placeholder="请输入民族" />
						</el-form-item>
					
					</el-col>
				</el-row>

				<el-row>
					<el-col :span="12">
						<el-form-item label="身份证号" prop="idcard">
							<el-input v-model="formData.idcard" placeholder="请输入身份证号" />
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="联系方式" prop="tel">
							<el-input v-model="formData.tel" placeholder="请输入联系方式" />
						</el-form-item>
						
						
					</el-col>
				</el-row>


				<el-row>
					<el-col :span="12">
						<el-form-item label="出生年月" prop="birthday">
							<el-date-picker v-model="formData.birthday" style="width: 100%;" placeholder="请选择出生年月"
								value-format="YYYY-MM-DD" type="date" />
						</el-form-item>
					
					</el-col>

					<el-col :span="12">
						<el-form-item label="转正时间" prop="zz_time">
							<el-date-picker v-model="formData.zz_time" style="width: 100%;" placeholder="请选择转正时间"
								value-format="YYYY-MM-DD" type="date" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :span="12">
						<el-form-item label="入党时间" prop="join_time">
							<el-date-picker v-model="formData.join_time" style="width: 100%;" placeholder="请选择入党时间"
								value-format="YYYY-MM-DD" type="date" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="进入支部时间" prop="entry_time">
							<el-date-picker v-model="formData.entry_time" style="width: 100%;" placeholder="请选择进入支部时间"
								value-format="YYYY-MM-DD" type="date" />
						</el-form-item>
					</el-col>	
					
				</el-row>
				<el-form-item label="文化程度" prop="edu_level">
					<el-input v-model="formData.edu_level" placeholder="请输入文化程度" />
				</el-form-item>
				<el-form-item label="照片" prop="image">
					<single-upload v-model="formData.image" />
				</el-form-item>

				<el-form-item label="排序" prop="sort">
					<el-input-number v-model="formData.sort" controls-position="right" :min="0" :max="10000"
						style="width: 100px" />
					<span class="ml-3" type="info">升序，0-10000之间</span>
				</el-form-item>

				<el-form-item label="备注" prop="mark">
					<el-input type="textarea" v-model="formData.mark"  placeholder="请输入备注" :autosize="{ minRows: 2, maxRows: 4 }" />
				</el-form-item>

			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleSubmit">确 定</el-button>
					<el-button @click="closeDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
	defineOptions({
		name: "Dangwei",
		inheritAttrs: false,
	});

	import { useRoute } from 'vue-router';

	import {
		getDataPage,
		updateData,
		getDataForm,
		addData,
		deleteData,
		listDzbOptions,
	} from "@/api/dangwei";
	import SingleUpload from "@/components/Upload/SingleUpload.vue";
	import { DataPageVO, DataQuery } from "@/api/dangwei/types";
	import { useTableFilterStore } from "@/store/modules/tableFilter";
	const TableFilter = useTableFilterStore();
	const strtype = ref('org')

	// 表格标题
	const cTitles = ["ID", "姓名", "党支部", "职位", "民族", "入党时间", "转正时间", "进入支部时间", "排序"];
	// 显示字段
	const sTitles = ["ID", "姓名", "党支部", "职位", "民族", "排序"];
	// 字段属性	
	const cColumns = [
		{ label: "ID", prop: "id", align: "center", width: 80 },
		{ label: "姓名", prop: "name", align: "center", minwidth: 150 },
		{ label: "职位", prop: "position", align: "center", minwidth: 150 },
		{ label: "党支部", prop: "dzb.name", align: "center", minwidth: 150 },
		{ label: "民族", prop: "nation", align: "center", width: 100 },
		{ label: "入党时间", prop: "join_time", align: "center", minwidth: 150 },
		{ label: "转正时间", prop: "zz_time", align: "center", minwidth: 150 },
		{ label: "进入支部时间", prop: "entry_time", align: "center", minwidth: 150 },
		{ label: "排序", prop: "sort", align: "center", width: 100 },
	]
	interface TableGlobalLocal {
		[key : string] : any; // 或者更具体的类型
	}
	// 列表渲染
	function cColumnsList() {
		const ColumnsList = (TableFilter.tableGlobalLocal as TableGlobalLocal)[strtype.value + '_checklist'];
		if (ColumnsList) {
			const columnMap : any = {}; // 创建一个对象来存储cColumns中label和对象的映射  
			// 预先建立label到对象的映射  
			for (const column of cColumns) {
				columnMap[column.label] = column;
			}
			const newList = [];
			for (const label of ColumnsList) {
				// 尝试从映射中获取对象  
				const foundColumn = columnMap[label];
				if (foundColumn) {
					// 如果找到了，则添加到newList中  
					newList.push(foundColumn);
				}
			}
			return newList;
		}
		else {
			return [];
		}
	};
	// 列表-数据列初始化
	function columnsInit() {
		const dropColStr : string = strtype.value + '_dropCol';
		const checklistStr : string = strtype.value + '_checklist';
		const drop_col : any = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr];
		const checklist = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr];
		if (!drop_col) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
		}
		if (!checklist) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
		}
	}




	const dzbOptions = ref<OptionType[]>([]);

	const dataFormRef = ref(ElForm);
	const loading = ref(false);
	const ids = ref<number[]>([]);
	const total = ref(0);
	const tableData = ref<any>([]);
	const multipleSelection = ref<any>([]);
	const menuLineVisible = ref(true);
	const rowR = ref<any>({});



	const route = useRoute();
	const queryParams = reactive<DataQuery>({
		page: 1,
		limit: 10,
	});

	const dialog = reactive<DialogOption>({
		visible: false,
	});

	const formData = reactive({
		id: undefined,
		did: "",//党支部
		name: "",//姓名
		gender: "",//性别
		nation: "",//民族
		tel: "",//电话号码
		idcard: "",//身份证号
		edu_level: "",//文化程度
		birthday: "",//出生年月日
		entry_time: "",//进入支部时间
		join_time: "",//入党时间
		zz_time: "",//转正时间
		role: "",//校色
		position: "",//职位
		image: "",//照片
		sort: 50,//排序
		mark: ""//备注
	});

	const rules = reactive({
		did: [{ required: true, message: "请选择党支部", trigger: "change" }],
		name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
		gender: [{ required: true, message: "请选择性别", trigger: "change" }],
		role: [{ required: true, message: "请选择角色", trigger: "change" }],
		position: [{ required: true, message: "请输入职位", trigger: "blur" }],
	});


	// 行菜单事件
	function rowMouse(row : any) {
		menuLineVisible.value = true
		rowR.value = row
	}
	// 数据多选事件
	function handleSelectionChange(val : any) {
		multipleSelection.value = val
	}
	// 操作按钮样式
	function buttonType(val : number) {
		if (val === 1) {
			return 'primary'
		} else {
			return 'info'
		}
	}
	// 操作
	function handleDo(row : any, act : string) {
		let uitem = {}
		switch (act) {
			case 'act_add':
				dialog.visible = true;
				dialog.title = "新增党委";
				resetForm();
				break
			case 'act_edit':
				dialog.visible = true;
				dialog.title = "修改党委信息";
				uitem = JSON.parse(JSON.stringify(row || multipleSelection.value[0]));
				getDataForm(uitem.id).then(({ data }) => {
					Object.assign(formData, data);
				});
				break
			case 'act_del':
				handleDelete(JSON.parse(JSON.stringify(row || multipleSelection.value[0])))
				break

			default:
		}
	}


	/**
	 * 查询
	 */
	function handleQuery() {
		loading.value = true;
		getDataPage(queryParams)
			.then(({ data }) => {
				tableData.value = data.list;
				total.value = data.count;
			})
			.finally(() => {
				loading.value = false;
			});
	}
	/**
	 * 重置查询
	 */
	function resetQuery() {

		handleQuery();
	}



	

	/**
	 * 表单提交
	 */
	function handleSubmit() {
		loading.value = true;
		dataFormRef.value.validate((valid : any) => {
			if (valid) {
				const Id = formData.id;
				if (Id) {
					updateData(Id, formData)
						.then(() => {
							ElMessage.success("修改成功");
							closeDialog();
							resetQuery();
						})
						.finally(() => (loading.value = false));
				} else {
					addData(formData)
						.then(() => {
							ElMessage.success("新增成功");
							closeDialog();
							resetQuery();
						})
						.finally(() => (loading.value = false));
				}
			}
		});
	}

	/**
	 * 关闭弹窗
	 */
	function closeDialog() {
		dialog.visible = false;
		resetForm();
	}

	/**
	 * 重置表单
	 */
	function resetForm() {
		dataFormRef.value.resetFields();
		dataFormRef.value.clearValidate();

	}

	/**
	 * 删除
	 */
	
	// 删除表单内容
	function handleDelete(row ?: any) {
		const Ids =row.id;
		if (!Ids) {
			ElMessage.warning("请勾选删除项");
			return;
		}	
		ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			loading.value = true;
			deleteData(Ids)
				.then(() => {
					ElMessage.success("删除成功");
					resetQuery();
				})
				.finally(() => (loading.value = false));
		});
	}

	onMounted(() => {
		listDzbOptions()
			.then(({ data }) => {
				dzbOptions.value = data;
				if (route.query.did) {
					queryParams.did = Number(route.query.did)
				}
				handleQuery();
			})

		columnsInit();
	});
</script>